<template>
  <view>
    <tn-form :model="form" ref="form" :labelWidth="180" :errorType="['message', 'toast']">

      <view class="card tn-padding-sm tn-margin-sm" v-for="(item, index) of form.data">
        <tn-form-item label="现场安全防护照片：" prop="invoicePhoto">
          <tn-image-upload :deleteable="false" :ref="'imageUpload' + index" :maxCount="1" :header="header" :action="action" :fileList="item.imgArr"></tn-image-upload>
        </tn-form-item>
        <tn-form-item label="备注：" prop="remark">
          <tn-input disabled type="textarea" v-model="item.remark" />
        </tn-form-item>
        <tn-form-item label="时间：" prop="createTime1">
          <uni-datetime-picker :disabled="true" :clearIcon="false" :border="false" placeholder="请选择时间" v-model="item.createTime1" />
        </tn-form-item>
        <view class="tn-flex tn-flex-row-right tn-margin-top">
          <tn-button @click="delitem(index)" backgroundColor="tn-bg-red" style="width: 20%; margin-left: 10rpx" fontColor="tn-color-white">删除</tn-button>
        </view>
      </view>

      <view class="card tn-padding-sm tn-margin-sm">
        <tn-form-item label="时间：" prop="createTime1">
          <uni-datetime-picker :clearIcon="false" :border="false" placeholder="请选择时间" v-model="form.createTime1" />
        </tn-form-item>
        <tn-form-item label="现场安全防护照片：" prop="invoicePhoto">
          <tn-image-upload :beforeUpload="beforeUpload" @on-success="onSuccess" :formData="formData" ref="imageUpload" :maxCount="1" :header="header" :action="action"></tn-image-upload>
        </tn-form-item>
        <tn-form-item label="备注：" prop="remark">
          <tn-input type="textarea" v-model="form.remark" />
        </tn-form-item>
        <view class="tn-flex tn-flex-row-right tn-margin-top">
          <tn-button @click="add" backgroundColor="tn-bg-blue" style="width: 80%; margin-right: 10%" fontColor="tn-color-white">保存</tn-button>
        </view>
      </view>
    </tn-form>
    <!-- <view class="tn-flex tn-flex-row-center tn-padding-xl">
      <tn-button @click="submit" backgroundColor="tn-bg-blue" style="width: 80%" fontColor="tn-color-white">保存</tn-button>
    </view> -->
    <tn-modal v-model="erweima" :custom="true">
      <view v-if="form.data.length > 1">
        <p class="title">现场安全防护照片</p>
        <view class="modal-box" style="max-height: 100vw; padding-top: 32px">
          <view
              v-for="(item, index) of form.data"
              :key="index"
              class="custom-modal-content tn-flex tn-flex-direction-column tn-flex-col-center"
              style="margin-bottom: 18px"
          >
            <canvas :id="'qrcode' + index" :canvas-id="'qrcode' + index" style="width: 30vw; height: 30vw"></canvas>
            <tn-button
                :class="'btn' + index"
                @click="downloadPDFFn(item, index)"
                backgroundColor="tn-bg-blue"
                style="width: 100%; margin-top: 16px"
                fontColor="tn-color-white"
            >
              下载图片{{ index + 1 }}
            </tn-button>
          </view>
        </view>
      </view>
      <template v-else>
        <view v-for="(item, index) of form.data" :key="index" class="custom-modal-content tn-flex tn-flex-direction-column tn-flex-col-center" style="margin-bottom: 18px">
          <p style="margin-bottom: 8px">现场安全防护照片</p>
          <canvas id="qrcode0" canvas-id="qrcode0" style="width: 200px; height: 200px"></canvas>
          <tn-button @click="downloadPDFFn(item, index)" backgroundColor="tn-bg-blue" style="width: 80%; margin-top: 16px" fontColor="tn-color-white">下载图片</tn-button>
        </view>
      </template>
    </tn-modal>
  </view>
</template>

<script>
let timer = null;
import config from '@/config';
import { getToken } from '@/utils/auth';
import { getJySiteSafety, addJySiteSafety, delJySiteSafety } from '@/api/jySiteSafety';
import UQRCode from '@/node_modules/uqrcodejs/uqrcode.js';
import dayjs from 'dayjs';
import {toast} from "@/utils/common";
export default {
  data() {
    return {
      os: {},
      erweima: false,
      dragAddress: '',
      url: '',
      action: config.baseUrl + '/exam/common/api/file/uploadSy',
      header: {
        token: getToken()
      },
      form: {
        data: [],
        invoicePhoto: '',
        remark: '',
        createTime1:''
      },
      formData:{
        syString: '2025-04-29 14:15:42  G18  K123+321'
      },
      rules: {}
    };
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.form.setRules(this.rules);
    uni.getStorage({
      key: 'TIANBAOID',
      success: (res) => {
        if (res.data) {
          this.getList(res.data);
          this.form.jyBaseId = res.data;
          // 延时回显
          setTimeout(()=>{
            this.form.createTime1 = dayjs().format('YYYY-MM-DD HH:mm:ss')
          },1000)
        }
      }
    });

    uni.getStorage({
      key: 'TIANBAOINFO',
      success: (res) => {
        if (res.data) {
          const item = res.data;
          // {{ item.highSpeed }} {{ item.direction }} K{{ item.startPoint }} + {{ item.endPoint }}
          this.formData.syString = `${dayjs().format('YYYY-MM-DD HH:mm:ss')} ${item.highSpeed} K${item.startPoint} + ${ item.endPoint }`
        }
      }
    });

    uni.getSystemInfo().then(res=>{
      this.os = res[1].osName
    })
  },
  onNavigationBarButtonTap(e) {
    if (!this.dragAddress) {
      return uni.showToast({
        title: '未生成PDF',
        icon: 'none'
      });
    }
    this.erweima = true;
    this.$nextTick(this.creatImg);
  },
  methods: {
    beforeUpload(index,list){
      timer = setTimeout(()=>{
        uni.showLoading({
          title: '上传中'
        });
      },500)
    },
    rotateSuccess(e){
      console.log('e.tempFilePath', e.tempFilePath)
      // uni.saveImageToPhotosAlbum({
      //  filePath:e.tempFilePath
      // })
    },
    onSuccess(e){
      this.$refs.imageUpload.lists[0].url = e.data.url;
      clearTimeout(timer);
      toast('图片上传成功')
    },
    downloadPDFFn(item, index) {
      if (!item.invoicePhoto) {
        return;
      }
      this.erweima = false;
      window.location.href = item.invoicePhoto;
    },
    creatImg() {
      this.form.data.forEach((data, index) => {
        // 获取uQRCode实例
        var qr = new UQRCode();
        // 设置二维码内容
        qr.data = data.invoicePhoto;
        // 设置二维码大小，必须与canvas设置的宽高一致
        qr.size = document.querySelector('.btn0')?.offsetWidth || 200;
        // 调用制作二维码方法
        qr.make();
        // 获取canvas上下文
        var canvasContext = uni.createCanvasContext(`qrcode${index}`, this); // 如果是组件，this必须传入
        // 设置uQRCode实例的canvas上下文
        qr.canvasContext = canvasContext;
        // 调用绘制方法将二维码图案绘制到canvas上
        qr.drawCanvas();
      });
    },
    add() {
      this.imgChange();
      if(!this.form.invoicePhoto){
        return toast('请上传照片')
      }
      const li = {
        remark: this.form.remark,
        invoicePhoto: this.form.invoicePhoto,
        jyBaseId: this.form.jyBaseId,
        createTime1: this.form.createTime1
      };
      addJySiteSafety(li).then((res) => {
        if (res.data === 1) {
          this.form.remark = '';
          this.form.invoicePhoto = '';
          this.$refs.imageUpload.clear();
          this.getList(this.form.jyBaseId);
          toast('保存成功')
        }
      });
    },
    delitem(index) {
      delJySiteSafety(this.form.data[index].id).then((res) => {
        console.log(res);
        if (res.data === 1) {
          this.getList(this.form.jyBaseId);
        }
      });
    },
    delImg() {
      delJySiteSafety(id).then((res) => {
        console.log('res', res);
      });
    },
    getList(id) {
      this.form.data = []
      getJySiteSafety(id).then((res) => {
        if (res.data) {
          this.form.data = res.data.map((item) => {
            return {
              ...item,
              imgArr: [{ url: item.invoicePhoto }]
            };
          });
          this.dragAddress = res.data.length > 0 ? true : false;
        }
      });
    },
    imgChange() {
      let arr = [];
      this.$refs.imageUpload.lists.forEach((val) => {
        if (val.progress == 100) {
          arr.push(val.response.data.url);
        }
      });
      this.form.invoicePhoto = arr.join();
    },
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // this.imgChange();
          addJySiteSafety(this.form.data).then((res) => {
            uni.navigateBack();
          });
          console.log('验证通过');
        } else {
          console.log('验证失败');
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.card {
  background-color: #fff;
  box-shadow: 0px 4px 20px 0px rgba(0, 3, 72, 0.1);
  border-radius: 8px;
}

.title {
  text-align: center;
  text-align: center;
  position: fixed;
  width: 68%;
  background: #ffffff;
  z-index: 9;
  margin-top: -22px;
  padding-top: 22px;
  margin-left: -1px;
}
.modal-box {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
::v-deep {
  .tn-form-item--left__content__label {
    font-weight: 700;
  }
}
</style>
